#!/usr/bin/env bash
set -e
set -o pipefail

## 正式环境
#ip_a=139.196.109.125
#path_a=/data/application/jars/
#prefix_a=
#
## 正式服务器中的测试
#ip_b=139.196.109.125
#path_b=/data/test/jars/
#prefix_b='test-'
#
## 内网104
ip_c=172.16.1.106
path_c=/data/application/jars/
prefix_c=
#
## 乐乐的电脑
#ip_d=139.196.109.125
#path_d=/data/application/jars/
#prefix_d=

Usage() {
  cat <<token
帮助说明
  deploy.sh [-lmnh] [-abc] [all | admin | api]

选择动作
  -l 打印日志
  -r 打包启动
  -n 不打包启动
  -h 帮助说明
选择环境
  -a 环境 ${ip_a} ${path_a}
  -b 环境 ${ip_b} ${path_b}
  -c 环境 ${ip_c} ${path_c}
  -d 环境 ${ip_d} ${path_d}

选择程序
  all | admin | api  选择部署哪个项目
token
}

# 动作
while getopts 'abcdlrnh' OPT; do
  case $OPT in
  a)
    ip_=${ip_a}
    path_=${path_a}
    prefix_=${prefix_a}
    ;;
  b)
    ip_=${ip_b}
    path_=${path_b}
    prefix_=${prefix_b}
    ;;
  c)
    ip_=${ip_c}
    path_=${path_c}
    prefix_=${prefix_c}
    ;;
  d)
    ip_=${ip_d}
    path_=${path_d}
    prefix_=${prefix_d}
    ;;
  l)
    # 打印日志
    action="log"
    ;;
  r)
    # 打包启动
    action="run"
    ;;
  n)
    # 不打包启动
    action="noPackageRun"
    ;;
  h)
    Usage
    exit 0
    ;;
  ?)
    Usage
    exit 1
    ;;
  esac
done
shift $(($OPTIND - 1))

echo "${ip_} ${path_} $[prefix_]"
set -x

# 判断
if [[ "${ip_}" == "" || "$action" == "" || ! $1 =~ (all|api|admin) ]]; then
  Usage
  exit 0
fi

# 打印日志
if [[ "$action" == 'log' ]]; then
  ssh root@${ip_} "docker logs -f --tail 350 ${prefix_}hoya-$1"
  exit 0
fi

# 打包
if [[ "$action" == 'run' ]]; then
  mvn clean && mvn package -Dmaven.skip.test=true || {
    echo "打包失败"
    exit 1
  }
fi

# 运行
if [[ "$action" =~ (run|Run) ]]; then
  if [[ "$1" == 'all' ]]; then
    scp ./hoya-api/target/hoya-api.jar ./hoya-admin/target/hoya-admin.jar root@${ip_}:${path_} &&
      ssh root@${ip_} "cd ${path_} &&  docker-compose -f docker-compose-file.yml restart"
  elif [[ "$1" == 'api' ]]; then
    scp ./hoya-api/target/hoya-api.jar root@${ip_}:${path_} &&
      ssh root@${ip_} "cd ${path_} &&  docker-compose -f docker-compose-file.yml restart ${prefix_}hoya-api && docker logs -f --tail 10 ${prefix_}hoya-api"
  elif [[ "$1" == 'admin' ]]; then
    scp ./hoya-admin/target/hoya-admin.jar root@${ip_}:${path_} &&
      ssh root@${ip_} "cd ${path_} &&  docker-compose -f docker-compose-file.yml restart ${prefix_}hoya-admin && docker logs -f --tail 10 ${prefix_}hoya-admin"
  fi
fi
